package filters;

import interfaces.IMap;



public class MedianFilter implements IFilter
{
	int R;
	int Histogram[];
	public MedianFilter(int r)
	{
		R=r;
		Histogram = new int[256];		
	}
	@Override
	public int ApplyFilter(int Px, int Py, IMap map) 
	{
		for(int i=0;i<256;i++)
			Histogram[i]=0;
		
		for (int y = -R; y < R+1; y++)
            for (int x = -R; x < R+1; x++)
            {            	
            	int C = ((int)map.Get(Px + x,Py + y)) & 255;
            	Histogram[C]++;            	
            }
		
		int sum=0;
		int level = ((R*2+1)*(R*2+1))/2;
		for(int i=0;i<256;i++)
		{
			sum+=Histogram[i];
			if(sum>=level)
				return i;
		}
		return 0;
	}	
}
